package org.xdq.反射机制;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Utils {

    private static boolean isUpperCase(char c){
        return !(c >= 'a' && c <= 'z');
    }

    public static <T> T copy(Object fromBean,Class<T> toBeanClass) throws IllegalAccessException, InstantiationException {
        Object toBean = toBeanClass.newInstance();
        copy(fromBean,toBean);
        return (T)toBean;
    }

    public static  void copy(Object fromBean,Object toBean)  {

        //1.获取两个Bean对象所属类的元类对象
        Class fromClass = fromBean.getClass();
        Class toClass = toBean.getClass();

        //2.获取fromBean的所有getter
        Method[] fromMds = fromClass.getMethods();
        for(Method fromMd : fromMds){
            String fromMdName = fromMd.getName();

            if(fromMdName.startsWith("get") &&
                    fromMdName.length()>3 &&
                    isUpperCase(fromMdName.charAt(3)) &&
                    fromMd.getParameterCount() ==0 &&
                    fromMd.getReturnType() != void.class
            ){
                String fieldName = fromMdName.substring(3);
                String toSetMdName = "set"+fieldName;
                try {
                    Method toSetMd = toClass.getMethod(toSetMdName, fromMd.getReturnType());
                    Object getMdReturnValue = fromMd.invoke(fromBean);//执行fromBean的get方法，获得返回值
                    toSetMd.invoke(toBean, getMdReturnValue);//执行toBean的set方法，将上述返回值赋值

                } catch (NoSuchMethodException e) {//如无匹配方法，则进行下一个方法的匹配
                    continue;
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }


    }
}
